import os
import re
import pymysql
from loguru import logger
import allure


# from common.handle_path import CONF_DIR
# from common.base_api import BaseApi


class HandleMysql:
    @allure.step('step:连接数据库')
    def __init__(self, **kwargs):
        # 连接到数据库
        try:
            self.con = pymysql.connect(charset="utf8", **kwargs)
        except Exception as e:
            logger.error(f'数据库连接失败，连接参数：{kwargs}')
            raise e
        else:
            # 创建一个游标
            self.cur = self.con.cursor()

    def get_one(self, sql):
        """获取查询到的第一条数据"""
        self.cur.execute(sql)
        self.con.commit()
        return self.cur.fetchone()

    def get_all(self, sql):
        """获取sql语句查询到的所有数据"""
        self.cur.execute(sql)
        self.con.commit()
        return self.cur.fetchall()

    def count(self, sql):
        """获取sql语句查询到的数量"""
        res = self.cur.execute(sql)
        self.con.commit()
        return res

    def close(self):
        # 关闭游标对象
        self.cur.close()
        # 断开连接
        self.con.close()

    def get_index_dict(self):
        index_dict = dict()
        index = 0
        for desc in self.cur.description:
            index_dict[desc[0]] = index
            index += 1
        return index_dict

    # mysql 结果集转换成list[dict]
    def get_sql_todict(self, sql):
        self.cur.execute(sql)
        data = self.cur.fetchall()
        index_dict = self.get_index_dict()
        res = []
        for i in data:
            d = dict()
            for ii in index_dict:
                d[ii] = i[index_dict[ii]]
            res.append(d)
        return res










# if __name__ == '__main__':
    # import common.base_api as b
    # p = os.path.join(b.CONF_DIR, 'config.yaml')
    # print(p)
    # a = b.BaseApi()
    # # print(p)
    # conf = a.get_yaml(p)
    # mysql = conf['mysql']
    # print(mysql)
#     db = HandleMysql(**mysql)
#     print(type(db))
#     print(db)
#     x = db.count('SELECT id FROM czt_testing.user WHERE id="16"')
#     print(x)

